package com.nwpu.hass.serviceimpl;

import com.nwpu.hass.domain.JsonResponse.DeviceBykeyword;
import com.nwpu.hass.domain.JsonResponse.IdleDevicesGroupResponse;
import com.nwpu.hass.service.ComputeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.*;

/**
 * @author alecHe
 * @desc ...
 * @date 2021-01-11 19:36:34
 */

@Service
public class ComputeServiceImpl {

    private static ComputeService computeService = null;

    @Autowired
    private EntityManager entityManager;



    public ComputeServiceImpl() throws RemoteException, NotBoundException, MalformedURLException {
    }

    public static ComputeService getInstance() throws RemoteException{
        if(null == computeService){
            try {
                computeService  = (ComputeService) Naming.lookup("computeService");
            }catch (NotBoundException | MalformedURLException e){
                throw new RemoteException();
            }
        }
        return computeService;

    }

    public Double computeScore(String msg,String catagoryName, String brand, String type) throws Exception {
        computeService = ComputeServiceImpl.getInstance();

        return computeService.serviceOffer(msg,catagoryName,brand,type);

    }

    public List<DeviceBykeyword> findByKeyword(String keyWord,List<IdleDevicesGroupResponse> list) throws Exception {

        List<DeviceBykeyword> res = new ArrayList<>();
        for(IdleDevicesGroupResponse item:list){
            double score = this.computeScore(keyWord,item.getFamily(),item.getType(),item.getDeviceName());
            if(score == 0) {
                continue;
            }
            res.add(DeviceBykeyword.view2entity(item,score));
        }
        Collections.sort(res);
        if(res.size() >= 30){
            return res.subList(0,30);
        }
        return res;
    }




}
